/**
 * 习惯控制器
 * 处理习惯相关的数据库操作
 */

import { BaseController, ensureDbInit, createResponse, createErrorResponse } from './BaseController'
import database from '../../utils/database'
import { generateId } from '../../mock/utils'

export class HabitsController extends BaseController {
  constructor() {
    super('habits')
  }

  /**
   * 获取习惯列表
   */
  async getHabitsList(params: {
    page?: number
    pageSize?: number
    category?: string
    isActive?: boolean
    search?: string
  } = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        category,
        isActive,
        search
      } = params || {}

      let whereClause = 'is_deleted = 0'
      let whereParams: any[] = []

      if (category) {
        whereClause += ' AND category_id = ?'
        whereParams.push(category)
      }

      if (isActive !== undefined) {
        whereClause += ' AND is_active = ?'
        whereParams.push(isActive ? 1 : 0)
      }

      if (search) {
        whereClause += ' AND (name LIKE ? OR description LIKE ?)'
        whereParams.push(`%${search}%`, `%${search}%`)
      }

      return await this.getList({
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'created_at DESC'
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取习惯列表失败')
    }
  }

  /**
   * 创建习惯
   */
  async createHabit(data: {
    name: string
    description?: string
    categoryId?: string
    icon?: string
    color?: string
    type?: string
    frequency?: any
    targetValue?: number
    unit?: string
    reminderEnabled?: boolean
    reminderTime?: string
  }) {
    try {
      await ensureDbInit()
      const habitId = generateId()
      const now = new Date().toISOString()

      const habitData = {
        id: habitId,
        user_id: 'current_user', // 简化实现
        name: data.name,
        description: data.description || '',
        category_id: data.categoryId || '',
        icon: data.icon || '',
        color: data.color || '#3498db',
        type: data.type || 'daily',
        frequency: JSON.stringify(data.frequency || {}),
        target_value: data.targetValue || 1,
        unit: data.unit || '',
        reminder_enabled: data.reminderEnabled ? 1 : 0,
        reminder_time: data.reminderTime || '',
        is_active: 1,
        created_at: now,
        updated_at: now,
        is_deleted: 0
      }

      await database.insert('habits', habitData)

      return createResponse({
        id: habitId,
        ...data,
        isActive: true,
        createdAt: now,
        updatedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '创建习惯失败')
    }
  }

  /**
   * 更新习惯
   */
  async updateHabit(id: string, data: any) {
    try {
      await ensureDbInit()
      const updateData = {
        ...data,
        updated_at: new Date().toISOString()
      }

      if (updateData.frequency) {
        updateData.frequency = JSON.stringify(updateData.frequency)
      }

      const rowsAffected = await database.update('habits', updateData, 'id = ? AND is_deleted = 0', [id])

      if (rowsAffected === 0) {
        return createErrorResponse('习惯不存在', 1003)
      }

      const detailResult = await this.getHabitDetail(id)
      return detailResult
    } catch (error: any) {
      return createErrorResponse(error.message || '更新习惯失败')
    }
  }

  /**
   * 删除习惯
   */
  async deleteHabit(id: string) {
    return await this.hardDelete(id)
  }

  /**
   * 获取习惯详情
   */
  async getHabitDetail(id: string) {
    try {
      await ensureDbInit()
      const habitsResult = await database.query(
        'SELECT * FROM habits WHERE id = ? AND is_deleted = 0',
        [id]
      )

      if (habitsResult.code !== 0) {
        return createErrorResponse(habitsResult.message || '查询习惯详情失败')
      }

      const habits = habitsResult.data || []
      if (habits.length === 0) {
        return createErrorResponse('习惯不存在', 1003)
      }

      const habit = habits[0]
      return createResponse({
        id: habit.id,
        name: habit.name,
        description: habit.description,
        categoryId: habit.category_id,
        icon: habit.icon,
        color: habit.color,
        type: habit.type,
        frequency: habit.frequency ? JSON.parse(habit.frequency) : {},
        targetValue: habit.target_value,
        unit: habit.unit,
        reminderEnabled: habit.reminder_enabled === 1,
        reminderTime: habit.reminder_time,
        isActive: habit.is_active === 1,
        createdAt: habit.created_at,
        updatedAt: habit.updated_at
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取习惯详情失败')
    }
  }

  /**
   * 标记习惯完成
   */
  async complete(id: string, data: {
    date?: string
    value?: number
    note?: string
  } = {}) {
    try {
      await ensureDbInit()
      const { date = new Date().toISOString().split('T')[0], value = 1, note = '' } = data

      const recordId = generateId()
      const now = new Date().toISOString()

      try {
        await database.insert('habit_records', {
          id: recordId,
          habit_id: id,
          date,
          value,
          note,
          created_at: now,
          updated_at: now,
          is_deleted: 0
        })
      } catch (error) {
        // 如果记录已存在，则更新
        await database.update(
          'habit_records',
          { value, note, updated_at: now },
          'habit_id = ? AND date = ? AND is_deleted = 0',
          [id, date]
        )
      }

      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '标记习惯完成失败')
    }
  }

  /**
   * 取消习惯完成
   */
  async uncomplete(id: string, data: { date?: string } = {}) {
    try {
      await ensureDbInit()
      const { date = new Date().toISOString().split('T')[0] } = data

      await database.delete(
        'habit_records',
        'habit_id = ? AND date = ?',
        [id, date]
      )

      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '取消习惯完成失败')
    }
  }

  /**
   * 获取习惯统计数据
   */
  async stats(id: string, params: {
    startDate?: string
    endDate?: string
  } = {}) {
    try {
      await ensureDbInit()
      const { startDate, endDate } = params

      let whereClause = 'habit_id = ? AND is_deleted = 0'
      let whereParams = [id]

      if (startDate) {
        whereClause += ' AND date >= ?'
        whereParams.push(startDate)
      }

      if (endDate) {
        whereClause += ' AND date <= ?'
        whereParams.push(endDate)
      }

      const recordsResult = await database.query(
        `SELECT * FROM habit_records WHERE ${whereClause} ORDER BY date DESC`,
        whereParams
      )

      if (recordsResult.code !== 0) {
        return createErrorResponse(recordsResult.message || '查询习惯统计数据失败')
      }

      const records = recordsResult.data || []
      const totalDays = records.length
      const totalValue = records.reduce((sum: number, record: any) => sum + record.value, 0)
      const avgValue = totalDays > 0 ? totalValue / totalDays : 0

      return createResponse({
        totalDays,
        totalValue,
        avgValue,
        records: records.map((record: any) => ({
          date: record.date,
          value: record.value,
          note: record.note
        }))
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取习惯统计失败')
    }
  }

  /**
   * 获取习惯历史记录
   */
  async history(id: string, params: {
    page?: number
    pageSize?: number
    startDate?: string
    endDate?: string
  } = {}) {
    try {
      await ensureDbInit()
      const {
        page = 1,
        pageSize = 20,
        startDate,
        endDate
      } = params

      let whereClause = 'habit_id = ? AND is_deleted = 0'
      let whereParams = [id]

      if (startDate) {
        whereClause += ' AND date >= ?'
        whereParams.push(startDate)
      }

      if (endDate) {
        whereClause += ' AND date <= ?'
        whereParams.push(endDate)
      }

      // 获取总数
      const countResult = await database.query(
        `SELECT COUNT(*) as count FROM habit_records WHERE ${whereClause}`,
        whereParams
      )

      if (countResult.code !== 0) {
        return createErrorResponse(countResult.message || '获取习惯历史记录总数失败')
      }

      const total = (countResult.data && countResult.data[0] && typeof countResult.data[0].count !== 'undefined')
        ? countResult.data[0].count
        : 0

      // 获取分页数据
      const offset = (page - 1) * pageSize
      const recordsResult = await database.query(
        `SELECT * FROM habit_records WHERE ${whereClause} ORDER BY date DESC LIMIT ? OFFSET ?`,
        [...whereParams, pageSize, offset]
      )

      if (recordsResult.code !== 0) {
        return createErrorResponse(recordsResult.message || '获取习惯历史记录失败')
      }

      const records = recordsResult.data || []

      return createResponse({
        list: records.map((record: any) => ({
          id: record.id,
          habitId: record.habit_id,
          date: record.date,
          value: record.value,
          note: record.note,
          createdAt: record.created_at,
          updatedAt: record.updated_at
        })),
        page,
        pageSize,
        total
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取习惯历史记录失败')
    }
  }
}

// 导出单例实例
export const habitsController = new HabitsController()